<template>
  <div>
    <vue-ueditor-wrap v-model="msg" :config="myConfig" @ready="ready" @beforeInit="addCustomButtom" :editor-dependencies="editorDependencies"></vue-ueditor-wrap>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-upload class="upload-demo" drag :action="url" :accept="accept" :before-upload="beforeUpload" :on-success="handleAvatarSuccess" :show-file-list="false">
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">拖拽文件到此处 或者 <em>点击上传</em></div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="UEditor">
import { computed, reactive, ref, shallowRef } from "vue";
import { VueUeditorWrap } from "vue-ueditor-wrap";
import { ElMessage, UploadRequestOptions, uploadProps } from "element-plus";
// import { uploadImg } from "@/api/modules/upload";
import { getToken } from "@/utils/cache";
import app from "@/constants/app";

let accept = ref("");
let title = ref("");
const url = `${app.api}/sys/oss/upload?token=${getToken()}`;
let myConfig: object = reactive({
  UEDITOR_HOME_URL: "assets/UEditor/",
  toolbars: [
    [
      "fullscreen",
      "source",
      "|",
      "undo",
      "redo",
      "|",
      "bold",
      "italic",
      "underline",
      "fontborder",
      "strikethrough",
      "superscript",
      "subscript",
      "removeformat",
      "formatmatch",
      "autotypeset",
      "blockquote",
      "pasteplain",
      "|",
      "forecolor",
      "backcolor",
      "insertorderedlist",
      "insertunorderedlist",
      "selectall",
      "cleardoc",
      "|",
      "rowspacingtop",
      "rowspacingbottom",
      "lineheight",
      "|",
      "customisable",
      "paragraph",
      "fontfamily",
      "fontsize",
      "|",
      "directionalityltr",
      "directionalityrtl",
      "indent",
      "|",
      "justifyleft",
      "justifycenter",
      "justifyright",
      "justifyjustify",
      "|",
      "touppercase",
      "tolowercase",
      "|",
      "imagenone",
      "imageleft",
      "imageright",
      "imagecenter",
      "|",
      "uploadImg",
      "uploadVideo",
      "horizontal",
      "|",
      "inserttable",
      "deletetable",
      "insertparagraphbeforetable",
      "insertrow",
      "deleterow",
      "insertcol",
      "deletecol",
      "mergecells",
      "mergeright",
      "mergedown",
      "splittocells",
      "splittorows",
      "splittocols",
      "charts",
      "|",
      "135editor"
    ]
  ],
  enableAutoSave: false, // 禁用自动保存
  autoFloatEnabled: false, // 关闭菜单悬浮
  initialFrameHeight: 500,
  autoHeightEnabled: false
});
let dialogVisible = ref(false);
let props = defineProps(["html"]);
const myUEditor = shallowRef();
type EmitProps = {
  (e: "update:html", val: string): void;
  (e: "check-validate"): void;
};
const emit = defineEmits<EmitProps>();
const msg = computed({
  get() {
    return props.html;
  },
  set(val: string) {
    // 防止富文本内容为空时，校验失败
    if (!myUEditor.value.getContent()) val = "";
    emit("update:html", val);
  }
});
const ready = (editorInstance: any) => {
  myUEditor.value = editorInstance;
};
// 自定义上传按钮
const addCustomButtom = () => {
  // @ts-ignore
  window.UE.registerUI(
    "uploadVideo",
    function (editor: any, uiName: any) {
      // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
      editor.registerCommand(uiName, {
        execCommand: function () {
          editor.execCommand("inserthtml", ``);
        }
      });
      // 参考http://ueditor.baidu.com/doc/#COMMAND.LIST
      // @ts-ignore
      let btn = new window.UE.ui.Button({
        name: "uploadVideo",
        title: "上传视频",
        cssRules: `background-position: -320px -20px;`,
        onclick: function () {
          // 渲染dialog
          title.value = "上传视频";
          accept.value = "video/*";
          dialogVisible.value = true;
          editor.execCommand(uiName);
        }
      });
      return btn;
    },
    51 /* 指定添加到工具栏上的那个位置，默认时追加到最后 */
  );
  // @ts-ignore
  window.UE.registerUI(
    "uploadImg",
    function (editor: any, uiName: any) {
      // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
      editor.registerCommand(uiName, {
        execCommand: function () {
          editor.execCommand("inserthtml", ``);
        }
      });
      // 参考http://ueditor.baidu.com/doc/#COMMAND.LIST
      // @ts-ignore
      let btn = new window.UE.ui.Button({
        name: "uploadImg",
        title: "上传图片",
        cssRules: `background-position: -380px 0px;`,
        onclick: function () {
          // 渲染dialog
          title.value = "上传图片";
          accept.value = "image/*";
          dialogVisible.value = true;
          editor.execCommand(uiName);
        }
      });
      return btn;
    },
    51 /* 指定添加到工具栏上的那个位置，默认时追加到最后 */
  );
};
// 引入的js文件
let editorDependencies: string[] = reactive(["ueditor.config.js", "ueditor.all.min.js", "lang/zh-cn/zh-cn.js", "135editor.js"]);
// 文件上传
// @ts-ignore
const handleAvatarSuccess: uploadProps["onSuccess"] = (response, uploadFile) => {
  if (response.code === 0) {
    try {
      if (title.value === "上传图片") {
        myUEditor.value.execCommand("insertHtml", `<img src="https://${response.data.src}" style="max-width: 100%">`);
      } else {
        myUEditor.value.execCommand("insertHtml", '<video src="https://' + response.data.src + '" class="playsinline" controls="true" preload="auto"  style="object-fit:fill;width:100%;max-width:360px;"></video>');
      }
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  } else {
    ElMessage.error(response.msg);
  }
};
// 上传之前
const beforeUpload = (file: any) => {
  if (title.value === "上传图片") {
    if (file.type.indexOf("image") === -1) {
      ElMessage({
        message: "请上传图片类型的文件",
        type: "warning"
      });
      return false;
    }
  } else {
    if (file.type.indexOf("video") === -1) {
      ElMessage({
        message: "请上传视频类型的文件",
        type: "warning"
      });
      return false;
    }
  }
};
</script>

<style lang="scss">
.edui-button.edui-for-135editor .edui-button-wrap .edui-button-body .edui-icon {
  background-image: url("http://static.135editor.com/img/icons/editor-135-icon.png") !important;
  background-size: 85%;
  background-position: center;
  background-repeat: no-repeat;
}

.edui-editor {
  width: 100% !important;
}

#edui1_iframeholder {
  width: 100% !important;
}

.edui-combox-body,
.edui-button-wrap {
  line-height: normal;
}
</style>
